<template>
  <div class="component-container">
    <div class="app-container">

      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增菜单</el-button>
        </el-form-item>
        <el-form-item prop="name">
          <el-input
              v-model="queryParams.name"
              :placeholder="$t('system.menu.nameM')"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
          >{{ $t('system.globalParam.Search') }}
          </el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">{{ $t('system.globalParam.Reset') }}</el-button>
        </el-form-item>
      </el-form>
      <!-- 数据表格 -->
      <el-table v-loading="loading"
                class="es-table"
                :data="menuList"
                highlight-current-row header-cell-class-name="app-table-head table-head-center" row-key="id" border
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                @row-click="handleRowClick"
                :header-cell-style="{  background: '#fafafa',   color: '#262626',  height: '54px'   }"
                :row-style="{ height: '68px'}">
        <el-table-column align="left" :label="$t('system.menu.numberM')">
          <template #default="scope">
            {{ scope.row.code }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('system.menu.nameM')" align="center" prop="name"/>
        <el-table-column :label="$t('system.menu.pathM')" align="left" prop="path"/>
        <el-table-column :label="$t('system.menu.typeM')" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.category === 1" type="success">{{ $t('system.menu.contents') }}</el-tag>
            <el-tag v-if="scope.row.category === 2" type="success">{{ $t('system.menu.Menu') }}</el-tag>
            <el-tag v-if="scope.row.category === 3" type="warning">{{ $t('system.menu.Button') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('system.menu.State')" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.visible === 1" type="success">{{ $t('system.menu.Display') }}</el-tag>
            <el-tag v-else type="info">{{ $t('system.menu.Hide') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('system.group.Sort')" align="left" width="100" prop="sort"/>
        <el-table-column :label="$t('system.globalParam.Operation')" align="center" width="200">
          <template #default="scope">
            <!--          <el-button type="success" :icon="Plus" circle plain @click.stop="handleAdd(scope.row)"/>-->
            <Plus class="operation-icon" color="#409eff" @click.stop="handleAdd(scope.row)"/>
            <!--          <el-button type="primary" :icon="Edit" circle plain @click.stop="handleUpdate(scope.row)"/>-->
            <Edit class="operation-icon" color="#409eff" @click.stop="handleUpdate(scope.row)"/>
            <!--          <el-button type="danger" :icon="Delete" circle plain @click.stop="handleDelete(scope.row)"/>-->
            <Delete class="operation-icon" color="#409eff" @click.stop="handleDelete(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹窗表单 -->
    <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" @close="cancel"
               width="750px">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto">
        <el-form-item :label="$t('system.menu.menuParent')" prop="parentId">
          <el-tree-select v-model="formData.parentId" :placeholder="$t('system.menu.Superior')" :data="menuOptions"
                          filterable :default-expanded-keys="[formData.parentId]" check-strictly/>
        </el-form-item>
        <el-form-item :label="$t('system.menu.typeM')">
          <el-radio-group v-model="formData.category" @change="handleMenuTypeChange">
            <el-radio label="1">{{ $t('system.menu.contents') }}</el-radio>
            <el-radio label="2">{{ $t('system.menu.Menu') }}</el-radio>
            <el-radio label="3">{{ $t('system.menu.Button') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('system.menu.numberM')" v-if="formData.category !== '3'" prop="code">
          <el-input v-model="formData.code" :placeholder="$t('system.menu.enterNumber')"/>
        </el-form-item>
        <el-form-item :label="$t('system.menu.numberB')" v-if="formData.category === '3'" prop="code">
          <el-input v-model="formData.code" placeholder="sys:user:add"/>
        </el-form-item>
        <el-form-item :label="formData.category === '3' ? $t('system.menu.nameB') : $t('system.menu.nameM')"
                      prop="name">
          <el-input v-model="formData.name"
                    :placeholder="formData.category === '3' ?$t('system.menu.enterBname') :$t('system.menu.enterMname') "/>
        </el-form-item>
        <el-form-item :label="$t('system.menu.enName')" prop="enName">
          <el-input v-model="formData.enName"
                    :placeholder="formData.category === '3' ?$t('system.menu.enterEnMname') :$t('system.menu.enterEnMname') "/>
        </el-form-item>
        <!-- 路由路径(浏览器地址栏显示) -->
        <el-form-item v-if="formData.category !== '3'" :label="$t('system.menu.Routing')" prop="path">
          <el-input v-if="formData.category === '1'" v-model="formData.path" :placeholder="$t('system.menu.note')"/>
          <el-input v-else v-model="formData.path" placeholder="user"/>
        </el-form-item>
        <!-- 组件页面完整路径 -->
        <el-form-item v-if="formData.category === '2'" :label="$t('system.menu.pathC')" prop="component">
          <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
            <!--            <template v-if="formData.parentId != '0'" #prepend>src/pages/</template>-->
            <!--            <template v-if="formData.parentId != '0'" #append>.vue</template>-->
            <template #prepend>src/pages/</template>
            <template #append>.vue</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('system.menu.Associated')">
          <el-table :data="formData.resourcesList" style="width: 100%;" max-height="250" border>
            <el-table-column fixed prop="value" :label="t('system.menu.Resource')">
              <template #default="scope">
                <el-form-item :prop="'resourcesList.' + scope.$index + '.value'"
                              :rules="{required: true,message:$t('system.menu.enterResources'), trigger: 'blur',}">
                  <el-input v-model="scope.row.value" :placeholder="$t('system.menu.interface')"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('system.globalParam.Operation')" width="100">
              <template #default="scope">
                <Delete class="operation-icon" @click.stop="deleteRow(scope.$index)"/>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="mt-4" style="width: 100%" @click="onAddItem">{{ $t('system.menu.Add') }}</el-button>
        </el-form-item>
        <el-form-item :label="$t('system.menu.routeJ')" v-if="formData.category !== '3'">
          <el-input v-model="formData.redirect" :placeholder="$t('system.menu.pathJ')" maxlength="50"/>
        </el-form-item>
        <el-form-item :label="$t('system.menu.Icon')" prop="icon">
          <SelectIcon v-model:name='formData.icon'/>
        </el-form-item>
        <el-form-item :label="$t('system.menu.State')">
          <el-radio-group v-model="formData.visible">
            <el-radio :label="1">{{ $t('system.menu.Display') }}</el-radio>
            <el-radio :label="0">{{ $t('system.menu.Hide') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('system.group.Sort')" prop="sort">
          <el-input v-model="formData.sort" :placeholder="$t('system.menu.sortS')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ $t('system.globalParam.Confirm') }}</el-button>
          <el-button @click="cancel">{{ $t('system.globalParam.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, onMounted, toRefs} from "vue";
import {Search, Plus, Edit, View, Refresh, Delete,} from "@element-plus/icons-vue";
import {ElForm, ElMessage, ElMessageBox, ElPopover} from "element-plus/es";
import {Dialog, Option} from "@/types/common";
import {TabMenuItem, TabMenuQueryParam, tabMenuService} from "@/services/resource/tabMenu";
import {useI18n} from 'vue-i18n'
import SelectIcon from '@/components/selectIcon/index.vue'

const {t} = useI18n()
const emit = defineEmits(["menuClick"]);
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const popoverRef = ref(ElPopover);

const state = reactive({
  loading: true,
  // 选中ID数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: {} as TabMenuQueryParam,
  menuList: [] as TabMenuItem[],
  dialog: {visible: false} as Dialog,
  formData: {
    parentId: "0",
    category: "1",
    code: "",
    name: "",
    visible: 1,
    resources: "",
    resourcesList: [{value: ""}],
    sort: "",
  } as TabMenuItem,
  rules: {
    parentId: [{required: true, message: t('system.menu.topmenuPlease'), trigger: "blur"}],
    code: [{required: true, message: t('system.menu.numberPlease'), trigger: "blur"}],
    name: [{required: true, message: t('system.menu.namePlease'), trigger: "blur"}],
    type: [{required: true, message: t('system.menu.menutypePlease'), trigger: "blur"}],
    path: [{required: true, message: t('system.menu.routingPlease'), trigger: "blur"}],
    component: [
      {required: true, message: t('system.menu.fullpathPlease'), trigger: "blur"},
    ],
    sort: [{required: true, message: t('system.menu.sortPlease'), trigger: "blur"}],
  },
  menuOptions: [] as Option[],
  currentRow: undefined,
  // Icon选择器显示状态
  iconSelectVisible: false,
  cacheData: {
    menuType: "",
    menuPath: "",
  },
});

const {
  loading,
  queryParams,
  menuList,
  dialog,
  formData,
  rules,
  menuOptions,
  iconSelectVisible,
  cacheData,
} = toRefs(state);

/**
 * 新增菜单
 * @param row
 */
async function handleAdd(row: any) {
  formData.value.id = undefined;
  await loadMenuData();
  state.dialog = {
    title: t('system.menu.menuAdd'),
    visible: true,
  };
  if (row.id) {
    // 行点击新增
    state.formData.parentId = `${row.id}`;
    //一级菜单：目录 菜单下面：按钮 else 菜单
    if (row.id == "0") {
      state.formData.category = "1";
    } else if (row.category == "2") {
      state.formData.category = "3";
    } else {
      state.formData.category = "2";
    }
  } else {
    // 工具栏新增
    state.formData.parentId = '0';
    state.formData.category = "1";
  }
}

/**
 * 编辑菜单
 */
async function handleUpdate(row: MenuFormData) {
  await loadMenuData();
  state.dialog = {
    title: t('system.menu.MenuEdit'),
    visible: true,
  };
  const id = row.id as string;
  getMenuDetail(id).then(({data}) => {
    state.formData = data;
    state.formData.category = `${data.category}`;
    state.formData.parentId = `${data.parentId}`;
    //资源
    state.formData.resourcesList = data.resources?.split(",").map((i) => {
      return {value: `${i}`};
    }) || [];
  });
}

/**
 * 删除菜单
 *
 * @param row
 */
function handleDelete(row: any) {
  if (row.children && row.children.length > 0) {
    ElMessage.error(t('system.menu.cannotDeleted'));
    return;
  }
  ElMessageBox.confirm(t('system.tenant.deletionConfirm') + row.name + t('system.tenant.it'), t('system.tenant.Warning'), {
    confirmButtonText: t('system.globalParam.Confirm'),
    cancelButtonText: t('system.globalParam.Cancel'),
    type: "warning",
  }).then(() => {
    deleteMenu(row.id).then(() => {
      ElMessage.success(t('system.tenant.deleteS'));
      handleQuery();
    });
  }).catch(() => ElMessage.info(t('system.tenant.Undeleted')));
}

/**
 * 菜单提交
 */
function submitForm() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.formData.id) {
        state.formData.resources = state.formData.resourcesList.map((i) => i.value).join(",");
        updateMenu(state.formData.id, state.formData).then(() => {
          ElMessage.success(t('system.menu.successfullyModified'));
          cancel();
          handleQuery();
        });
      } else {
        state.formData.resources = state.formData.resourcesList.map((i) => i.value).join(",");
        addMenu(state.formData).then(() => {
          ElMessage.success(t('system.menu.successNew'));
          cancel();
          handleQuery();
        });
      }
    }
  });
}

/**
 * 加载菜单下拉树
 */
async function loadMenuData() {
  const menuOptions: any[] = [];
  await listMenuOptions().then(({data}) => {
    const menuOption = {value: '0', label: t('system.menu.menuTop'), children: data};
    menuOptions.push(menuOption);
    state.menuOptions = menuOptions;
  });
}

/**
 * 选择图标后事件
 */
function selected(name: string) {
  state.formData.icon = name;
  state.iconSelectVisible = false;
}

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  emit("menuClick", null);
  state.loading = true;
  listByQuery().then(({data}) => {
    state.menuList = data;
    state.loading = false;
  });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

function handleRowClick(row: any) {
  state.currentRow = JSON.parse(JSON.stringify(row));
  emit("menuClick", row);
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  dataFormRef.value.resetFields();
  state.dialog.visible = false;
}

/**
 * 资源添加删除
 */
const onAddItem = () => {
  formData.value.resourcesList.push({
    value: "",
  });
};
const deleteRow = (index: number) => {
  formData.value.resourcesList.splice(index, 1);
};

onMounted(() => {
  handleQuery();
});
</script>
